<template>
    <div class="order-management">
        <!-- 空状态提示 -->
        <div v-if="!orders || orders.length === 0" class="empty-state">
            <p class="empty-text">您还没有订单哦~</p>
            <button v-if="!isLoggedIn" class="login-btn" @click="login">登录查看订单</button>
        </div>
        <!-- 订单列表 -->
        <div v-else class="order-list">
            <div 
                class="order-card"
                v-for="(order, index) in orders"
                :key="order.id"
            >
                <!-- 订单头部：订单号、状态、时间 -->
                <div class="order-header">
                    <span class="order-id">订单号：{{ order.id }}</span>
                    <span class="status {{ getStatusClass(order.status) }}">
                        {{ order.status }}
                    </span>
                    <span class="order-time">{{ formatDate(order.createdAt) }}</span>
                </div>

                <!-- 商家信息 -->
                <div class="shop-info">
                    <h3 class="shop-name">商家：{{ order.products[0]?.shopName || '未知商家' }}</h3>
                </div>

                <!-- 商品列表 -->
                <div class="products-list">
                    <div v-if="order.products.length === 0" class="empty-product">
                        <p>该订单暂无商品</p>
                    </div>
                    <div 
                        class="product-item"
                        v-for="(product, pIndex) in order.products"
                        :key="pIndex"
                    >
                        <!-- 增加图片加载失败的处理 -->
                        <img 
                            :src="product.image_url || '/default-image.png'" 
                            alt="product" 
                            class="product-image"
                            @error="handleImageError($event, product)"
                        />
                        <div class="product-info">
                            <span class="product-name">{{ product.name || '未命名商品' }}</span>
                            <span class="product-price">单价：¥{{ product.price || '0' }}</span>
                            <span class="product-quantity">数量：x{{ product.quantity || '1' }}</span>
                        </div>
                    </div>
                </div>

                <!-- 订单总计 & 再来一单按钮 -->
                <div class="order-footer">
                    <span class="total-price">总计：¥{{ order.totalPrice || '0' }}</span>
                    <button 
                        class="reorder-btn" 
                        @click="reorder(order)"
                    >
                        再来一单
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const orders = ref([]);
const isLoggedIn = ref(localStorage.getItem("isLoggedIn") === "true");

// 获取当前用户
const getCurrentUser = () => {
  return localStorage.getItem("currentUser");
};

// 从后端加载订单数据（按用户隔离）
const loadOrders = async () => {
  const currentUser = getCurrentUser();
  if (!currentUser) {
    console.error("未获取到用户信息，无法加载订单");
    return;
  }
  
  try {
    // 请求指定用户的订单数据
    const response = await axios.get(`http://localhost:3000/orders?userId=${currentUser}`);
    orders.value = response.data;
    console.log('从后端加载的用户订单数据:', orders.value);
  } catch (error) {
    console.error('加载订单失败:', error);
    ElMessage.error('加载订单失败，请重试');
  }
};

// 监听路由变化和登录状态变化
watch(
  [() => [route.path, route.params], isLoggedIn],
  () => {
    if (isLoggedIn.value) {
      loadOrders();
    } else {
      orders.value = [];
    }
  },
  { immediate: true }
);

onMounted(() => {
  if (!isLoggedIn.value) {
    console.log("用户未登录，无法加载订单");
    return;
  }
  
  loadOrders();
  console.log("订单管理组件已挂载");
});

// 格式化日期（示例：将 ISO 格式转为本地日期时间）
const formatDate = (dateString) => {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
        console.error('Invalid date:', dateString);
        return '未知日期';
    }
    
    // 格式化日期为本地格式
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
};

// 处理图片加载失败
const handleImageError = (event, product) => {
    product.image_url = '/default-image.png';
    event.target.src = product.image_url;
};

// 再来一单功能
const reorder = (order) => {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    order.products.forEach(product => {
        const existingProduct = cart.find(item => item.id === product.productId);
        if (existingProduct) {
            existingProduct.quantity += product.quantity;
        } else {
            cart.push({ 
                id: product.productId,
                name: product.name,
                price: product.price,
                image_url: product.image_url,
                shopName: product.shopName,
                quantity: product.quantity,
                isChecked: false,
                stock_quantity: 100 // 默认有库存，实际应从后端获取
            });
        }
    });
    localStorage.setItem('cart', JSON.stringify(cart));
    ElMessage.success("已重新添加到购物车！");
    router.push("/main/cart"); // 跳转回购物车
};

// 状态颜色映射
const getStatusClass = (status) => {
    return status === "待接单"? "status-pending" : 
           status === "已完成"? "status-completed" : 
           status === "已取消"? "status-cancelled" : "";
};

// 登录函数
const login = () => {
    router.push("/login");
};
</script>


<style scoped>
.order-management {
    margin-top: 60px;
    padding: 20px;
    min-height: 80vh;
}

.order-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.order-card {
    background: #ffffff;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    background-color: #f8f8f8 !important; /* 临时浅色背景 */
    border: 1px solid #ddd !important; /* 临时边框 */
    margin-bottom: 15px !important;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #efefef;
}

.status-pending {
    color: #e05649;
    border: 1px solid #e05649;
    padding: 3px 8px;
    border-radius: 20px;
}

.shop-info {
    text-align: left;
    margin-bottom: 15px;
    color: #666;
}

.products-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
}

.product-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border: 1px solid #efefef;
    border-radius: 10px;
}

.product-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
}

.product-info {
    display: flex;
    flex-direction: column;
    gap: 5px;
    flex: 1;
}

.order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 15px;
    border-top: 1px solid #efefef;
}

.total-price {
    font-size: 18px;
    font-weight: 600;
    color: #e05649;
}

.reorder-btn {
    padding: 8px 20px;
    background: #e05649;
    color: white;
    border: none;
    border-radius: 25px;
    cursor: pointer;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 300px;
}

.empty-text {
    font-size: 18px;
    color: #999;
    margin-bottom: 20px;
}

.login-btn {
    padding: 10px 20px;
    background-color: #e05649;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
</style>